package com.lin.gameserver.session;

import com.lin.gameserver.websocket.MessageLogger;

import jakarta.websocket.Session;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 游戏会话，封装WebSocket会话，提供与客户端通信的功能
 */
public class GameSession {
    private static final AtomicLong ID_GENERATOR = new AtomicLong(0);
    
    private final String sessionId;
    private final Session webSocketSession;
    private int playerId;
    private String account;
    private long lastActiveTime;
    private boolean authenticated;
    
    /**
     * 构造方法
     *
     * @param webSocketSession WebSocket会话
     */
    public GameSession(Session webSocketSession) {
        this.sessionId = generateSessionId();
        this.webSocketSession = webSocketSession;
        this.lastActiveTime = System.currentTimeMillis();
        this.authenticated = false;
    }
    
    /**
     * 发送二进制消息
     *
     * @param data 二进制数据
     * @throws IOException 发送失败时抛出异常
     */
    public void sendBinaryMessage(byte[] data) throws IOException {
        if (webSocketSession.isOpen()) {
            MessageLogger.logSent(sessionId, data);
            webSocketSession.getBasicRemote().sendBinary(ByteBuffer.wrap(data));
        } else {
            throw new IOException("WebSocket session is closed");
        }
    }
    
    /**
     * 关闭会话
     */
    public void close() {
        try {
            if (webSocketSession.isOpen()) {
                webSocketSession.close();
                MessageLogger.logSessionEvent(sessionId, "Session closed");
            }
        } catch (IOException e) {
            MessageLogger.logSessionEvent(sessionId, "Error closing session: " + e.getMessage());
        }
    }
    
    /**
     * 更新最后活动时间
     */
    public void updateActiveTime() {
        this.lastActiveTime = System.currentTimeMillis();
    }
    
    /**
     * 检查会话是否过期
     *
     * @param timeoutMs 超时时间（毫秒）
     * @return 是否过期
     */
    public boolean isExpired(long timeoutMs) {
        return System.currentTimeMillis() - lastActiveTime > timeoutMs;
    }
    
    /**
     * 生成唯一的会话ID
     *
     * @return 会话ID
     */
    private String generateSessionId() {
        return "session_" + System.currentTimeMillis() + "_" + ID_GENERATOR.incrementAndGet();
    }
    
    /**
     * 设置认证状态
     *
     * @param playerId 玩家ID
     * @param account 账号
     */
    public void setAuthenticated(int playerId, String account) {
        this.playerId = playerId;
        this.account = account;
        this.authenticated = true;
        MessageLogger.logSessionEvent(sessionId, "Session authenticated: playerId=" + playerId + ", account=" + account);
    }
    
    // Getters
    
    public String getSessionId() {
        return sessionId;
    }
    
    public int getPlayerId() {
        return playerId;
    }
    
    public String getAccount() {
        return account;
    }
    
    public long getLastActiveTime() {
        return lastActiveTime;
    }
    
    public boolean isAuthenticated() {
        return authenticated;
    }
    
    public Session getWebSocketSession() {
        return webSocketSession;
    }
} 